export default {
  install(Vue) {
    Vue.prototype.$html = {

      /**
       * 匹配 img 标签的 src 值，若开头不是 http、https 则加上完整域名
       * @param {Object} text
       */
      replaceImgSrc: function(text, baseUrl) {
        if (!!!text) return '';

        let imgExp = /<img [^>]*src=['"]([^'"]+)[^>]*>/gi;

        let imgs = text.match(imgExp);
        imgs?.forEach(it => {
          let srcValue = it.replace(imgExp, '$1');
          if (srcValue.slice(0, 4) === 'http' || srcValue.slice(0, 5) === 'https') {} else {
            text = text.replace(new RegExp(srcValue, 'g'), `${baseUrl}${srcValue}`);
          }
        });
        return this.composeImgStyle(text);
      },

      /**
       * 匹配 img 标签的 style 值，修改宽度占满、高度自适应
       * 1.去掉 img 标签里的 style、width、height 属性
       * 2.修改所有 style 里的 width 属性为 max-width:100%;
       * 3.去掉 <br>、<br/> 标签
       * 4.img 标签添加 style 属性为 max-width:100%;height:auto;
       * @param {Object} text
       */
      composeImgStyle: function(text) {
        if (!!!text) return '';

        text = text.replace(/<img[^>]*>/gi, (match, capture) => {
          match = match.replace(/style='[^']+'/gi, '').replace(/style="[^"]+"/gi, '');
          match = match.replace(/width='[^']+'/gi, '').replace(/width="[^"]+"/gi, '');
          match = match.replace(/height='[^']+'/gi, '').replace(/height="[^"]+"/gi, '');
          return match;
        });
        text = text.replace(/style="[^"]+"/gi, (match, capture) => {
          match = match.replace(/width:[^;]+;/gi, 'max-width:100%;');
          return match;
        });
        text = text.replace(/<br[^>]*>/gi, '').replace(/<br[^>]*\/>/gi, '');
        text = text.replace(/<img/gi,
          "<img style='max-width:100%;width:100%;height:auto;display:inline-block;margin:0rpx auto;'");
        return text;
      },

    }
  }
}
